//
//  RHExamineDetailVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/7/28.
//

#import "RHExamineDetailVC.h"
#import "RHEnterpriseBasicInfoCell.h"
#import "RHAgencyApplyInfoCell.h"
#import "RHAgencyApplyModel.h"

@interface RHExamineDetailVC ()<UITableViewDelegate,UITableViewDataSource,QMUITextViewDelegate>
@property (nonatomic ,strong) UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *pdfFileArr;

@property(nonatomic,strong)QMUITextView *textView;

@property(nonatomic, strong)QMUILabel *countLab;

@property(nonatomic ,strong)RHApplicationDetailModel *model;

@property(nonatomic ,strong)NSArray *titlesArr;
@end

@implementation RHExamineDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:CFTabViewBgColor];
    
    
//    NSLog(@"RHExamineDetailVC self.model--->%@",self.model.yy_modelDescription);
    _titlesArr = @[@"Enterprise qualifications and experience",
                         @"Financial position",
                         @"Market analysis and business plan",
                         @"Sites and facilities",
                         @"Personnel composition and team management",
                         @"Promotion and Marketing Plan",
                         @"Other supporting materials"];
    
    [self getAuditDetail];
    [self setupUI];
}

#pragma mark ----- 获取审核详情 ------
-(void)getAuditDetail
{
    kWeakSelf;
    [QMUITips showLoadingInView:self.view];
    NSString *url = [NSString stringWithFormat:@"%@%ld",H_countryRegionName,self.Id];
    [RHApplicationDetailModel startGetWithCompletionAPIKey:url argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            weakSelf.model = resultModel.data;
            weakSelf.textView.text = weakSelf.model.remark;
            //组装pdf文件相关信息
            weakSelf.pdfFileArr = [NSMutableArray array];
            for (int i = 0; i< weakSelf.titlesArr.count ; i++) {
                RHAgencyApplyModel *apply_model = [[RHAgencyApplyModel alloc]init];
                apply_model.title = weakSelf.titlesArr[i];
                RHPdfFileModel *attch = [[RHPdfFileModel alloc]init];
                [self getDescribeWith:apply_model detailModel:self.model index:i];
                
                [weakSelf.pdfFileArr addObject:apply_model];
                [weakSelf.tableView reloadData];
            }
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

- (void)setupUI{
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHEnterpriseBasicInfoCell class] forCellReuseIdentifier:@"RHEnterpriseBasicInfoCell"];
    [_tableView registerClass:[RHAgencyApplyInfoCell class] forCellReuseIdentifier:@"RHAgencyApplyInfoCell"];
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
       
    }];
    
    
    //添加审核窗口
    if(_isAudit){
        UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, kScaleW(280))];
        bgView.backgroundColor = CFTabViewBgColor;
        _tableView.tableFooterView = bgView;
        
        UIView *auditView = kView;
        auditView.backgroundColor = [UIColor whiteColor];
        auditView.layer.cornerRadius = 8;
        auditView.layer.masksToBounds = YES;
        [bgView addSubview:auditView];
        
        QMUILabel *commentLab = [[QMUILabel alloc]init];
        commentLab.text =  @"Review Comments";
        commentLab.font = [UIFont systemFontOfSize:18];
        commentLab.textAlignment = NSTextAlignmentLeft;
        [auditView addSubview:commentLab];
        
        QMUITextView *commentTextView = [[QMUITextView alloc]init];
        commentTextView.backgroundColor = kCOLOR_HEX(@"F4F4F4");
        commentTextView.layer.cornerRadius = 8;
        commentTextView.layer.masksToBounds = YES;
        commentTextView.placeholder = @"Please input review comments";
        commentTextView.placeholderColor = [UIColor colorWithHexString:@"3F4443" alpha:0.5];
        [auditView addSubview:commentTextView];
        commentTextView.delegate = self;
        _textView = commentTextView;
        
        self.countLab = [[QMUILabel alloc]init];
        [self.countLab setTextColor:[UIColor colorWithHexString:@"3F4443" alpha:0.4]];
        [commentTextView addSubview:self.countLab];
        self.countLab.font = [UIFont systemFontOfSize:11];
        self.countLab.text = @"0/100";
        [self.countLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(commentTextView).offset(-3);
            make.right.equalTo(commentTextView).offset(-3);
            
        }];
        
        QMUIButton *agreeBtn = [[QMUIButton alloc]init];
        agreeBtn.tag = 1;
        [agreeBtn setTitle:@"Agree" forState:UIControlStateNormal];
        [agreeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        agreeBtn.backgroundColor = CMainColorGreen;
        agreeBtn.layer.cornerRadius = 5;
        agreeBtn.layer.masksToBounds = YES;
        [bgView addSubview:agreeBtn];
        [agreeBtn addTarget:self action:@selector(auditAction:) forControlEvents:UIControlEventTouchUpInside];
        
        QMUIButton *rejectBtn = [[QMUIButton alloc]init];
        rejectBtn.tag = 2;
        [rejectBtn setTitle:@"Refuse" forState:UIControlStateNormal];
        [rejectBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        rejectBtn.backgroundColor = CFTabViewBgColor;
        rejectBtn.layer.cornerRadius = 5;
        rejectBtn.layer.borderColor = kCOLOR_HEX(@"CCCCCC").CGColor;
        rejectBtn.layer.borderWidth = 1;
        rejectBtn.layer.masksToBounds = YES;
        [bgView addSubview:rejectBtn];
        [rejectBtn addTarget:self action:@selector(auditAction:) forControlEvents:UIControlEventTouchUpInside];
        
        [auditView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.top.mas_offset(15);
            make.right.mas_offset(-15);
        }];
        
        [commentLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.top.mas_offset(15);
            make.height.offset(25);
        }];
        
        [commentTextView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(commentLab);
            make.top.equalTo(commentLab.mas_bottom).offset(15);
            make.right.mas_offset(-20);
//            make.height.offset(kScaleW(80));
            make.bottom.equalTo(auditView).offset(-15);
        }];
        [agreeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(kScaleW(30));
            make.top.equalTo(auditView.mas_bottom).offset(20);
            make.bottom.equalTo(bgView).offset(-20);
            make.height.offset(kScaleW(45));
        }];
        
        [rejectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(agreeBtn.mas_right).offset(kScaleW(30));
            make.right.mas_offset(kScaleW(-30));
            make.centerY.equalTo(agreeBtn);
            make.width.height.equalTo(agreeBtn);
        }];
        
        kWeakSelf;
        [[RACSignal merge:@[commentTextView.rac_textSignal,RACObserve(commentTextView, text)]]subscribeNext:^(NSString  *_Nullable text) {
            weakSelf.countLab.text = [NSString stringWithFormat:@"%ld/100",text.length];
        }];
        
    }else{
        //提交审核者
            UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, kScaleW(200))];
            bgView.backgroundColor = CFTabViewBgColor;
            _tableView.tableFooterView = bgView;
            
            UIView *auditView = kView;
            auditView.backgroundColor = [UIColor whiteColor];
            auditView.layer.cornerRadius = 8;
            auditView.layer.masksToBounds = YES;
            [bgView addSubview:auditView];
            
            QMUILabel *commentLab = [[QMUILabel alloc]init];
            commentLab.text =  @"Review Comments";
            commentLab.font = [UIFont systemFontOfSize:18];
            commentLab.textAlignment = NSTextAlignmentLeft;
            [auditView addSubview:commentLab];
            
            QMUITextView *commentTextView = [[QMUITextView alloc]init];
            commentTextView.userInteractionEnabled = NO;
            commentTextView.backgroundColor = kCOLOR_HEX(@"F4F4F4");
            commentTextView.layer.cornerRadius = 8;
            commentTextView.layer.masksToBounds = YES;
            commentTextView.text = self.model.remark;
            commentTextView.placeholderColor = [UIColor colorWithHexString:@"3F4443" alpha:0.5];
            commentTextView.textColor = [UIColor colorWithHexString:@"000000" alpha:0.4];
            [auditView addSubview:commentTextView];
            _textView = commentTextView;
            
//            QMUIButton *resubmitBtn = [[QMUIButton alloc]init];
//            resubmitBtn.tag = 1;
//            [resubmitBtn setTitle:@"Resubmit" forState:UIControlStateNormal];
//            [resubmitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//            resubmitBtn.backgroundColor = CMainColorGreen;
//            resubmitBtn.layer.cornerRadius = 5;
//            resubmitBtn.layer.masksToBounds = YES;
//            [bgView addSubview:resubmitBtn];
//            [resubmitBtn addTarget:self action:@selector(recommitAction) forControlEvents:UIControlEventTouchUpInside];
            
            [auditView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_offset(15);
                make.top.mas_offset(15);
                make.right.mas_offset(-15);
                make.bottom.mas_offset(-15);
            }];
            
            [commentLab mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_offset(15);
                make.top.mas_offset(15);
                make.height.offset(25);
            }];
            
            [commentTextView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(commentLab);
                make.top.equalTo(commentLab.mas_bottom).offset(15);
                make.right.mas_offset(-20);
    //            make.height.offset(kScaleW(80));
                make.bottom.equalTo(auditView).offset(-15);
            }];
//            [resubmitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.left.mas_offset(kScaleW(30));
//                make.right.mas_offset(kScaleW(-30));
//                make.top.equalTo(auditView.mas_bottom).offset(20);
//                make.bottom.equalTo(bgView).offset(-20);
//                make.height.offset(kScaleW(45));
//            }];
           

    }
   
}



-(void)getDescribeWith:(RHAgencyApplyModel*)model detailModel:(RHApplicationDetailModel*)detailModel index:(int)index
{
    switch (index) {
        case 0:{
            model.des_content = detailModel.certificationDescribe;//企业资质与经验
            NSMutableArray *cerArr = [NSMutableArray array];
            [detailModel.certificationFile enumerateObjectsUsingBlock:^(RHlisence  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                RHPdfFileModel *model = [[RHPdfFileModel alloc]init];
                model.fileName = obj.name;
                model.fileSize = obj.fileSize;
                [cerArr addObject:model];
            }];
            model.attachments = cerArr;
        }
            break;
        case 1:{
            model.des_content = detailModel.financeDescribe;//账务状况
            NSMutableArray *finaceArr = [NSMutableArray array];
            [detailModel.financeFile enumerateObjectsUsingBlock:^(RHlisence  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                RHPdfFileModel *model = [[RHPdfFileModel alloc]init];
                model.fileName = obj.name;
                model.fileSize = obj.fileSize;
                [finaceArr addObject:model];
            }];
            model.attachments = finaceArr;
        }
            break;
        case 2:{
            model.des_content = detailModel.planDescribe;//市场分析
            NSMutableArray *planArr = [NSMutableArray array];
            [detailModel.planFile enumerateObjectsUsingBlock:^(RHlisence  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                RHPdfFileModel *model = [[RHPdfFileModel alloc]init];
                model.fileName = obj.name;
                model.fileSize = obj.fileSize;
                [planArr addObject:model];
            }];
            model.attachments = planArr;
        }
            break;
        case 3:{
            model.des_content = detailModel.siteDescribe;//场地设施
            NSMutableArray *siteArr = [NSMutableArray array];
            [detailModel.siteFile enumerateObjectsUsingBlock:^(RHlisence  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                RHPdfFileModel *model = [[RHPdfFileModel alloc]init];
                model.fileName = obj.name;
                model.fileSize = obj.fileSize;
                [siteArr addObject:model];
            }];
            model.attachments = siteArr;
            
        }
            break;
        case 4:{
            model.des_content = detailModel.teamDescribe;//人员组成
            NSMutableArray *teamArr = [NSMutableArray array];
            [detailModel.teamFile enumerateObjectsUsingBlock:^(RHlisence  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                RHPdfFileModel *model = [[RHPdfFileModel alloc]init];
                model.fileName = obj.name;
                model.fileSize = obj.fileSize;
                [teamArr addObject:model];
            }];
            model.attachments = teamArr;
        }
            break;
        case 5:{
            model.des_content = detailModel.marketingDescribe;//推广
            NSMutableArray *marketArr = [NSMutableArray array];
            [detailModel.marketingFile enumerateObjectsUsingBlock:^(RHlisence  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                RHPdfFileModel *model = [[RHPdfFileModel alloc]init];
                model.fileName = obj.name;
                model.fileSize = obj.fileSize;
                [marketArr addObject:model];
            }];
            model.attachments = marketArr;
        }
            break;
        case 6:{
            model.des_content = detailModel.otherDescribe;//其他
            NSMutableArray *atherArr = [NSMutableArray array];
            [detailModel.otherFile enumerateObjectsUsingBlock:^(RHlisence  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                RHPdfFileModel *model = [[RHPdfFileModel alloc]init];
                model.fileName = obj.name;
                model.fileSize = obj.fileSize;
                [atherArr addObject:model];
            }];
            model.attachments = atherArr;
        }
            break;
        default:

            break;
    }
}


#pragma mark ----- 审核 -----
-(void)auditAction:(UIButton*)sender
{
    if(self.textView.text.length < 10 || self.textView.text.length>100){
        [QMUITips showError:@"Please enter 10 to 100 characters"];
        return;
    }
    
    [QMUITips showLoading:@"auditing...." inView:self.view];
    NSString *remark = self.textView.text.length > 0? self.textView.text : @"";
    [BaseModel startWithCompletionAPIKey:H_partnerAudit argument:@{@"audit":@(sender.tag),@"remark":remark,@"partnerId":@(self.model.audit_id)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"audit successful"];
            if(self.finishBlock) self.finishBlock();
            [self.navigationController popViewControllerAnimated:YES];
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if(![text isEqualToString:@""]){
        if(textView.text.length + text.length >100){
            return NO;
        }
    }
    return YES;
}

-(void)recommitAction{
    
}


#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.pdfFileArr.count+1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 45;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}
-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return  [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, kUI_WINDOW_W, 0.01f)];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 40)];
    QMUILabel *lab = [[QMUILabel alloc]initWithFrame:CGRectMake(15, 12, kUI_WINDOW_W-30, 25)];
    lab.font = [UIFont systemFontOfSize:17];
    
    lab.text = @"Enterprise Basic Information";
    if(section>0){
        RHAgencyApplyModel *model = self.pdfFileArr[section-1];
        lab.text = model.title;
    }
    [headerView addSubview:lab];
    return headerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section >0){
        RHAgencyApplyInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHAgencyApplyInfoCell"];
        cell.layer.cornerRadius = 8;
        cell.layer.masksToBounds = YES;
        cell.backgroundColor = [UIColor whiteColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.data = self.pdfFileArr[indexPath.section-1];
        [cell hideAddBtn];
        return cell;
    }
    
    RHEnterpriseBasicInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHEnterpriseBasicInfoCell"];
    cell.infoModel = self.model;
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.contentView.layer.cornerRadius = 8;
    cell.contentView.layer.masksToBounds = YES;
    return cell;
}

@end
